#include "mark_read_notice_command.h"
#include "service/backend_service.h"
#include "command_executor.h"
#include <QDebug>
#include <QUrl>
#include <QNetworkRequest>
#include <QJsonDocument>
#include <QJsonParseError>

MarkReadNoticeCommand::MarkReadNoticeCommand(QObject *parent)
    : BaseCommand(parent)
    , m_pendingNoticeId("")
{
}

MarkReadNoticeCommand::~MarkReadNoticeCommand()
{
}

void MarkReadNoticeCommand::setNetworkAccessManager(QNetworkAccessManager *networkManager)
{
    // 如果之前已经设置了 networkManager，先断开旧的连接
    if (m_networkManager) {
        disconnect(m_networkManager, &QNetworkAccessManager::finished,
                   this, &MarkReadNoticeCommand::handleMarkReadNoticeResponse);
    }
    
    BaseCommand::setNetworkAccessManager(networkManager);
    
    // 连接网络请求完成信号
    if (m_networkManager) {
        connect(m_networkManager, &QNetworkAccessManager::finished,
                this, &MarkReadNoticeCommand::handleMarkReadNoticeResponse);
    }
}

bool MarkReadNoticeCommand::execute(const QString &noticeId)
{
    if (!isValid()) {
        qDebug() << "MarkReadNoticeCommand: BackendService 或 QNetworkAccessManager 未设置";
        emit markReadNoticeCompleted(-1, "BackendService 或 QNetworkAccessManager 未设置", noticeId);
        return false;
    }
    
    if (noticeId.isEmpty()) {
        qDebug() << "MarkReadNoticeCommand: 通知ID为空";
        emit markReadNoticeCompleted(-1, "通知ID为空", noticeId);
        return false;
    }
    
    qDebug() << "MarkReadNoticeCommand: 开始标记通知为已读，通知ID:" << noticeId;
    
    // 检查是否有accessToken，如果没有则先获取
    if (!ensureAccessToken()) {
        // 如果没有选中的公司ID，无法获取accessToken
        if (!m_backendService || m_backendService->loadSelectedCompanyId().isEmpty()) {
            qDebug() << "MarkReadNoticeCommand: 没有选中的公司ID，无法获取accessToken";
            emit markReadNoticeCompleted(-1, "没有选中的公司ID，无法获取accessToken", noticeId);
            return false;
        }
        // 正在获取 token，保存待处理的通知ID
        m_pendingNoticeId = noticeId;
        return true; // 返回true表示已发起获取token的请求
    }
    
    // 获取 accessToken
    QString accessToken = CommandExecutor::getAccessToken();
    
    // 获取 baseUrl
    QString baseUrl = getBaseUrl();
    
    // 构建请求URL
    QString url = buildRequestUrl(baseUrl, noticeId);
    
    qDebug() << "MarkReadNoticeCommand: 发送标记已读请求到:" << url;
    
    // 创建网络请求
    QNetworkRequest request = createRequest(url, "PUT", "MarkReadNoticeCommand/1.0");
    
    // 添加token到请求头
    addTokenToRequest(request, accessToken);
    
    // 发送PUT请求
    QNetworkReply *reply = m_networkManager->put(request, QByteArray());
    if (!reply) {
        qDebug() << "MarkReadNoticeCommand: 创建网络请求失败";
        emit markReadNoticeCompleted(-1, "创建网络请求失败", noticeId);
        return false;
    }
    
    // 设置请求类型属性和通知ID
    reply->setProperty("requestType", "markReadNotice");
    reply->setProperty("noticeId", noticeId);
    
    qDebug() << "MarkReadNoticeCommand: 已发送标记已读请求";
    
    return true;
}

void MarkReadNoticeCommand::handleMarkReadNoticeResponse(QNetworkReply *reply)
{
    // 检查对象是否仍然有效
    if (!isValid()) {
        qDebug() << "MarkReadNoticeCommand: 对象已被销毁，忽略响应";
        if (reply) {
            reply->deleteLater();
        }
        return;
    }
    
    if (!reply) {
        qDebug() << "MarkReadNoticeCommand: 标记已读响应为空";
        if (isValid()) {
            emit markReadNoticeCompleted(-1, "标记已读响应为空", "");
        }
        return;
    }
    
    QString requestType = reply->property("requestType").toString();
    if (requestType != "markReadNotice") {
        // 不是标记已读请求，忽略
        reply->deleteLater();
        return;
    }
    
    QString noticeId = reply->property("noticeId").toString();
    
    // 检查网络错误
    if (reply->error() != QNetworkReply::NoError) {
        int errorCode = reply->error();
        QString errorString = reply->errorString();
        qDebug() << "MarkReadNoticeCommand: 标记已读网络请求错误:" << errorString;
        if (isValid()) {
            emit markReadNoticeCompleted(errorCode, "网络错误: " + errorString, noticeId);
        }
        reply->deleteLater();
        return;
    }
    
    // 读取响应数据
    QByteArray responseData = reply->readAll();
    qDebug() << "MarkReadNoticeCommand: 收到响应数据长度:" << responseData.length();
    
    // 解析JSON响应
    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData, &parseError);
    
    // 再次检查对象是否仍然有效
    if (!isValid()) {
        qDebug() << "MarkReadNoticeCommand: 对象已被销毁，忽略响应解析";
        reply->deleteLater();
        return;
    }
    
    if (parseError.error != QJsonParseError::NoError) {
        qDebug() << "MarkReadNoticeCommand: JSON解析错误:" << parseError.errorString();
        if (isValid()) {
            emit markReadNoticeCompleted(-1, "JSON解析错误: " + parseError.errorString(), noticeId);
        }
        reply->deleteLater();
        return;
    }
    
    if (!jsonDoc.isObject()) {
        qDebug() << "MarkReadNoticeCommand: 响应不是有效的JSON对象";
        if (isValid()) {
            emit markReadNoticeCompleted(-1, "响应不是有效的JSON对象", noticeId);
        }
        reply->deleteLater();
        return;
    }
    
    QJsonObject response = jsonDoc.object();
    parseMarkReadNoticeResponse(response, noticeId);
    
    reply->deleteLater();
}

void MarkReadNoticeCommand::parseMarkReadNoticeResponse(const QJsonObject &response, const QString &noticeId)
{
    // 检查对象是否仍然有效
    if (!isValid()) {
        qDebug() << "MarkReadNoticeCommand: 对象已被销毁，忽略响应解析";
        return;
    }
    
    qDebug() << "MarkReadNoticeCommand: 解析标记已读响应";
    
    // 检查响应状态
    int resultCode = 0;
    QString message = "成功";
    
    // 检查是否有错误信息
    if (response.contains("error")) {
        resultCode = -1;
        message = response["error"].toString();
        qDebug() << "MarkReadNoticeCommand: 服务器返回错误:" << message;
    } else if (response.contains("code")) {
        resultCode = response["code"].toInt();
        if (resultCode != 0) {
            message = response.contains("message") ? response["message"].toString() : "未知错误";
            qDebug() << "MarkReadNoticeCommand: 服务器返回错误代码:" << resultCode << "消息:" << message;
        }
    }
    
    // 最后一次检查对象是否仍然有效
    if (!isValid()) {
        qDebug() << "MarkReadNoticeCommand: 对象已被销毁，无法发送完成信号";
        return;
    }
    
    // 发送完成信号
    emit markReadNoticeCompleted(resultCode, message, noticeId);
}

QString MarkReadNoticeCommand::buildRequestUrl(const QString &baseUrl, const QString &noticeId)
{
    return baseUrl + "/message/api/message/notice/read?noticeId=" + noticeId;
}

